/************************************************************************************/
/*  Program name CAPGLIMP_ALLOC_BATCH.sql                                        	*/
/*  Creater:  NIP Karen (PCCW - UniHub)                                         	*/
/*************   History   *************************                                */
/* 24 JAN, 2006   NIP Karen         First created                                   */
/************************************************************************************/
SET SERVEROUTPUT ON SIZE 1000000;

DECLARE
	lv_Prog_ID		VARCHAR2(100)	:=	'CAPGLIMP_ALLOC_BATCH';

	lv_Scc_Count	NUMBER	:=	0;
	lv_Err_Count	NUMBER	:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';

	CURSOR Cur_F IS
	SELECT
		*
	FROM
		CRST_GL_ALLOC_BATCHES;
	
	lv_Next_Seq_ID		NUMBER;
	
BEGIN
	UPDATE
		GL_ALLOC_BATCHES
	SET	
		NAME	=	CAPBRIMP_MAPPING.RenameStr(SUBSTR(NAME,1,4), NAME)
	WHERE ALLOCATION_BATCH_ID IN
		(
		SELECT 
			ALLOCATION_BATCH_ID
		FROM 
			CRST_GL_ALLOC_BATCHES
		);
	
	FOR C1 IN Cur_F LOOP
		BEGIN
			SELECT	GL_ALLOC_BATCHES_S.NextVal
			INTO	lv_Next_Seq_ID
			FROM	DUAL;

			INSERT	INTO CRST_GL_ALLOC_BATCHES_MAP	VALUES
			(
			C1.ALLOCATION_BATCH_ID,
			CAPBRIMP_MAPPING.RenameStr(SUBSTR(C1.NAME,1,4), C1.NAME),
			C1.CHART_OF_ACCOUNTS_ID,
			lv_Next_Seq_ID,
			C1.NAME,
			CAPBRIMP_COMMON.GetCOAIDfromFlexStrCode(C1.ID_FLEX_STR_CODE)
			);
			
			INSERT INTO GL_ALLOC_BATCHES
			VALUES
			(
			lv_Next_Seq_ID,
			C1.name,
			CAPBRIMP_COMMON.GetCOAIDfromFlexStrCode(C1.ID_FLEX_STR_CODE),
			C1.validation_status,
			C1.actual_flag,
			C1.last_update_date,
			CAPBRIMP_COMMON.GetUser(C1.last_updated_name),
			C1.creation_date,
			CAPBRIMP_COMMON.GetUser(C1.created_name),
			C1.last_update_login,
			C1.validation_request_id,
			C1.description
			);
		EXCEPTION
			WHEN OTHERS THEN
				DBMS_OUTPUT.Put_Line(SQLERRM);
				lv_Err_Count	:=	lv_Err_Count + 1;
		END;
		lv_Scc_Count	:=	lv_Scc_Count	+	1;
	END LOOP;
	
	IF	lv_Err_Count	>	0	THEN
		ROLLBACK;
	END IF;
	
	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
	) VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count-lv_Err_Count,
		lv_Err_Msg
	);
	
	COMMIT;
END;
/